using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerSprintingState : PlayerMovingState
{
    private PlayerSprintData sprintData;
    private bool keepSprinting;
    private float startTime;
    private bool shouldResetSprintState;
    
    public PlayerSprintingState(PlayerMovementMachine playerMovementMachine) : base(playerMovementMachine)
    {
        sprintData = StateMachine.Player.Data.PlayerGroundedData.SprintData;
    }

#region IState Methods
    public override void Enter()
    {
        base.Enter();
        StateMachine.ReusableData.MovementSpeedModify = sprintData.SpeedModify;
        StateMachine.ReusableData.CurrentJumpForce = airborneData.JumpData.StrongForce;
        shouldResetSprintState = true;
        startTime = Time.time;
        StartAnimation(StateMachine.Player.AnimationData.SprintParameterHash);
        
    }

    public override void Update()
    {
        base.Update();
        
        if (keepSprinting)
            return;

        if (Time.time < startTime + sprintData.SprintToRunTime)
            return;

        StopSprinting();
    }

    public override void Exit()
    {
        base.Exit();

        if (shouldResetSprintState)
        {
            keepSprinting = false;
        }
        
        StopAnimation(StateMachine.Player.AnimationData.SprintParameterHash);
    }
#endregion

#region Main Methods
    private void StopSprinting()
    {
        if (StateMachine.ReusableData.InputMovement == Vector2.zero)
        {
            StateMachine.ChangeState(StateMachine.IdlingState);
            return;
        }
        
        StateMachine.ChangeState(StateMachine.RunningState);
    }
#endregion
    
#region Reuseable Methods
    protected override void AddInputActionsCallBacks()
    {
        base.AddInputActionsCallBacks();
        StateMachine.Player.PlayerInput.PlayerActions.Sprint.performed += OnSprintPerformed;
    }

    protected override void RemoveInputActionsCallBacks()
    {
        base.RemoveInputActionsCallBacks();
        StateMachine.Player.PlayerInput.PlayerActions.Sprint.performed -= OnSprintPerformed;
    }

    protected override void OnFall()
    {
        shouldResetSprintState = false;
        base.OnFall();
    }
#endregion

#region Input Methods
    protected override void OnMovementCanceled(InputAction.CallbackContext context)
    {
        StateMachine.ChangeState(StateMachine.HardStoppingState);
    }

    protected override void OnJumpPerformed(InputAction.CallbackContext context)
    {
        shouldResetSprintState = false;
        base.OnJumpPerformed(context);
    }

    private void OnSprintPerformed(InputAction.CallbackContext context)
    {
        keepSprinting = true;
        StateMachine.ReusableData.ShouldSprint = true;
    }
#endregion
}